﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SLLottery.LotteryView;
using SLLottery.Common;
using SLLottery.LotterySrv;
using System.Windows.Threading;
using System.Threading;
namespace SLLottery.Controls
{

    public partial class TouZhuCtrl : UserControl
    {
        private LotteryServiceClient srv;
        public LotteryType lotteryType = LotteryType.SSC;
        public int PlayType = 1;
        public string PlayTypeName = string.Empty;
        public bool isShow = true;
        public bool isHandled = false;
        public NumPanel numPanel
        {
            get;
            set;
        }
        public RadioButtonPanel rbPanel
        {
            get;
            set;
        }
        public TouZhuCtrl()
        {
            InitializeComponent();
            srv = WcfProxy.GetProxy;
            this.btnClear.Click += new RoutedEventHandler(btnClear_Click);
            srv.GetCapitalInfoCompleted += new EventHandler<GetCapitalInfoCompletedEventArgs>(srv_GetCapitalInfoCompleted);
            this.Loaded += new RoutedEventHandler(TouZhuCtrl_Loaded);
        }
        void btnClear_Click(object sender, RoutedEventArgs e)
        {
            List<NumButton> listNumButton = numPanel.GetNumButton();
            if (listNumButton.Count == 0)
            {
                numPanel.GetNumText().Text = "";
            }
            foreach (Controls.NumButton nb in listNumButton)
            {
                nb.SetClicked(false);
            }
            NumBasket.Items.Clear();
            this.lbBetCount.Text = "0";
            if (MainPage.playTypeRadio==47||MainPage.playTypeRadio==52)
            {
                MainPage.dicWs.Clear();
            }
        }
        void TouZhuCtrl_Loaded(object sender, RoutedEventArgs e)
        {
            if (!isShow)
            {
                this.cmdPanel.Visibility = Visibility.Collapsed;
                this.tbNum.Visibility = Visibility.Collapsed;
                this.Direction.Text = "逆向";
                this.Direction.Tag = LotteryOrientation.Reverse;
                this.Direction.Foreground = new SolidColorBrush(Common.MyColor.ConvertColor("#ff2ADC16"));
                this.DirectionInfo.Text = "（中奖时用户输，不中奖时用户赢）";
                this.DirectionInfo.Foreground = new SolidColorBrush(Common.MyColor.ConvertColor("#ff2ADC16"));
                this.NumBasket.Visibility = Visibility.Collapsed;
                this.btBonus.Visibility = Visibility.Collapsed;
                this.touzhuBtPanel.SetValue(Grid.ColumnProperty, 1);
                this.touzhuBtPanel.SetValue(Grid.RowProperty, 1);
            }
            else
                this.Direction.Tag = LotteryOrientation.Positive;
            List<PlayTypeRadioInfo> list = App.Session[Constant.PLAYTYPERADIO_SESSION] as List<PlayTypeRadioInfo>;
            PlayTypeRadioInfo ptri=list.Where(p => p.PlayTypeRadioID == MainPage.playTypeRadio).FirstOrDefault();
            Constant.Multiple = (int)ptri.Multiple;
            Constant.BaseScale = ptri.BaseScale;
            Constant.BaseMinScale = ptri.MinScale;
            InitPage();
            //SetMultiple();
            //LotteryServiceClient _srv = WcfProxy.GetProxy;
            //_srv.GetMultipleByPlayTypeIdAsync((int)PlayType);
            //_srv.GetMultipleByPlayTypeIdCompleted += (s, er) =>
            //{
            //    Multiple = er.Result;
            //    InitPage();
            //};
        }
        void InitPage()
        {
            this.btBonus.IsEnabled = true;
            Constant.MaxScale = BonusCalc.GetMaxScale();
            Constant.MinScale = BonusCalc.GetMinScale();
            Constant.MaxBonusPct = BonusCalc.GetMaxBonusPct();
            SetBonus();
            //if ((PlayType)PlayType == SLLottery.Common.PlayType._3DBddw
            //  || (PlayType)PlayType == SLLottery.Common.PlayType._Bddw
            //  || lotteryType == LotteryType.SSQ
            //  || (PlayType)PlayType == SLLottery.Common.PlayType._Rbdw)
            //{
            //    #region
            //    if (!App.Session.ContainsKey(Constant.PLAYTYPE_SESSION)
            //       || App.Session[Constant.PLAYTYPE_SESSION] == null)
            //    {
            //        srv.GetPlayTypeInfoAsync();
            //        this.btBonus.IsEnabled = false;
            //    }
            //    else
            //    {
            //        this.btBonus.IsEnabled = true;
            //        List<PlayTypeInfo> list = (List<PlayTypeInfo>)App.Session[Constant.PLAYTYPE_SESSION];
            //        PlayTypeInfo type = (from r in list
            //                             where r.PlayTypeID == PlayType
            //                             select r).FirstOrDefault();
            //        Constant.MaxScale = type.ScaleMaxValue;
            //        Constant.MinScale = type.ScaleMinValue;
            //        Constant.MaxBonusPct = type.BonusPctMaxValue;
            //        SetBonus();
            //    }
            //    #endregion
            //}
            //else
            //{
            //    this.btBonus.IsEnabled = true;
            //    Constant.MaxScale = BonusCalc.GetMaxScale(Multiple, lotteryType);
            //    Constant.MinScale = BonusCalc.GetMinScale(Multiple, lotteryType);
            //    Constant.MaxBonusPct = BonusCalc.GetMaxBonusPct(Multiple, lotteryType);
            //    SetBonus();
            //}
        }
        public string DirectionText
        {
            set { this.Direction.Text = value; }
            get { return this.Direction.Text; }
        }
        public string DirectionInfoText
        {
            set { this.DirectionInfo.Text = value; }
            get { return this.DirectionInfo.Text; }
        }
        private void btBonus_Click(object sender, RoutedEventArgs e)
        {
            Double bonusPct = Convert.ToDouble(this.lbBackPct.Text.Replace("%", ""));
            Double bonus = Convert.ToDouble(this.lbBonus.Text);
            Double scale = Convert.ToDouble(this.lbScale.Text);
            ChangeBonusWindow bw = new ChangeBonusWindow(bonusPct, scale, bonus, Constant.Multiple, lotteryType, PlayType);
            bw.Show();
            bw.Closed += (s, er) =>
                {
                    bool? result = bw.DialogResult;
                    if (result.HasValue && result.Value)
                    {
                        List<string> list = (List<string>)bw.Tag;
                        lbBonus.Text = list[0];
                        lbScale.Text = list[1];
                        lbBackPct.Text = list[2];
                    }
                };
        }
        bool isSysSet = false;
		/// <summary>
		/// 选中事件处理，删除选中项
		/// </summary> 
        private void NumBasket_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (isSysSet)
                return;
            DeleteSeleted de = new DeleteSeleted(DeleteSelected);
            Dispatcher.BeginInvoke(de, NumBasket.Items[NumBasket.SelectedIndex]);
            isSysSet = false;
        }
        delegate void DeleteSeleted(Object item);
		/// <summary>
		/// 删除选中项
		/// </summary>
		/// <param name="item"></param>
        void DeleteSelected(Object item)
        {
            if (NumBasket.Items.Count > 0)
            {
                isSysSet = true;
                NumBasket.Items.Remove(item);
				// 重新计算注数
                lbBetCount.Text = BetCountCalc.GetBetCount
                      (NumBasket, (PlayType)PlayType, numPanel.isWriten,
                       ((PlayTypeRadio)Convert.ToInt32(rbPanel.GetChoosedRadioButton().Tag.ToString())).ToString()
                      ).ToString();
                isSysSet = false;
            }
        }
        public void SetBonus()
        {
            if (Constant.Multiple == 1000)
            {
                this.btBonus.IsEnabled = false;
            }
            User user = App.Session[Constant.USERINFO_SESSION] as User;
            lbBonus.Text = BonusCalc.GetBonus(user.Bonus);
            lbScale.Text = BonusCalc.GetScale(user.Bonus);
            lbBackPct.Text = user.Bonus.ToString("F2") + "%";
            LotteryServiceClient _srv = WcfProxy.GetProxy;
            _srv.GetBonusInfoAsync(App.Session[Constant.USERNAME_SESSION].ToString(), PlayType, (int)lotteryType,MainPage.playTypeRadio);
            _srv.GetBonusInfoCompleted += (s, e) =>
            {

                if (e.Result != null)
                {
                    //当管理员后台修改了最大奖金和返点后比较用户保存的返点，如果用户保存返点大于当前最大返点则将用户的保存返点重置为用户默认返点
                    if (e.Result.BackPct > Constant.MaxBonusPct)
                    {
                        srv.UpdateBonusAsync(new BonusInfo
                        {
                            BackPct = user.Bonus,
                            LotteryTypeID = (int)lotteryType,
                            PlayTypeID = PlayType,
                            UserID = user.UserId
                        });
                        return;
                    }
                    lbBackPct.Text = e.Result.BackPct.ToString("F2") + "%";
                    lbBonus.Text = BonusCalc.GetBonus(e.Result.BackPct);
                    lbScale.Text = BonusCalc.GetScale(e.Result.BackPct);
                    //lbBonus.Text = e.Result.Bonus.ToString();
                    //lbScale.Text = e.Result.Scale.ToString();
                }
                else
                {
                    lbBonus.Text = BonusCalc.GetBonus(user.Bonus);
                    lbScale.Text = BonusCalc.GetScale(user.Bonus);
                    lbBackPct.Text = user.Bonus.ToString("F2") + "%";
                }
            };
        }
        public string GetBetNums()
        {
            if (!isShow)
                return numPanel.GetChoosedNum();
            string betNums_str = string.Empty;
            for (int i = 0; i < NumBasket.Items.Count; i++)
            {
                betNums_str += NumBasket.Items[i].ToString();
                if (i != NumBasket.Items.Count - 1)
                    betNums_str += "$";
            }
            return betNums_str;
        }
        private void btBet_Click(object sender, RoutedEventArgs e)
        {
            if (isHandled)
            {
                MessageBox.Show("错误发生");
                return;
            }
            isHandled = true;
            int betCount = 0;
            if (isShow)//正向
            {
                if (NumBasket.Items.Count == 0)
                {
                    Messager.Show("没有选择投注号码");
                    isHandled = false;
                    return;
                }
                betCount = BetCountCalc.GetBetCount
                   (NumBasket, (PlayType)PlayType, numPanel.isWriten,
                    ((PlayTypeRadio)Convert.ToInt32(rbPanel.GetChoosedRadioButton().Tag.ToString())).ToString());
            }
            else//反向
            {
                string str = numPanel.GetChoosedNum();
                if (str.Length == 0)
                {
                    Messager.Show("没有选择投注号码");
                    isHandled = false;
                    return;
                }
                if (!App.Session.ContainsKey(Constant.REVERSEODDS_SESSION) || App.Session[Constant.REVERSEODDS_SESSION] == null
                    || (App.Session[Constant.REVERSEODDS_SESSION] as List<Dictionary<string, string>>).Count == 0)
                {
                    Messager.Show("已经封单或者正在开奖中，暂时不能购买!");
                    isHandled = false;
                    return;
                }

                betCount = BetCountCalc.GetBetCount(str, (PlayType)PlayType);
            }
            double eachNumPoint = 0;
            if (!Double.TryParse(lbEachNumPoint.Text.Trim(), out eachNumPoint))
            {
                Messager.Show("单个号码下单分数不是有效的数字!");
                isHandled = false;
                return;
            }
            if (!Common.Common.ValidateBetMoney(lbEachNumPoint.Text))
            {
                Messager.Show("单个号码下单分数不是有效的正数!");
                isHandled = false;
                return;
            }
            string[] eachs = lbEachNumPoint.Text.Split('.');
            if (eachs.Length == 2 && eachs[1].Length > 1)
            {
                Messager.Show("单个号码下单分数小数点后最多只能1位(即精确到角)!");
                isHandled = false;
                return;
            }
            if (eachNumPoint > Constant.MaxOneBetMoney || eachNumPoint < Constant.MinOneBetMoney)
            {
                Messager.Show(string.Format("单个号码下单分数范围:{0}-{1}!",
                    Constant.MinOneBetMoney.ToString(), Constant.MaxOneBetMoney.ToString()));
                isHandled = false;
                return;
            }
            if (betCount > Constant.MaxBetCount)
            {
                Messager.Show(string.Format("一次下注最多{0}注号码!", Constant.MaxBetCount));
                isHandled = false;
                return;
            }
            double betMoney = betCount * Convert.ToDouble(lbEachNumPoint.Text);
            if (betMoney > Constant.MaxBetMoney)
            {
                Messager.Show(string.Format("一次下注最多{0}分数!", Constant.MaxBetMoney));
                isHandled = false;
                return;
            }
            if (lbScale.Text == "-" || lbBonus.Text == "-" || lbBackPct.Text == "-")
            {
                Messager.Show("赔率尚未加载完成,请稍等!");
                isHandled = false;
                return;
            }
            LotteryServiceClient wcfclient = WcfProxy.GetProxy;
            if (!isShow)
            {
                wcfclient.GetRemaindCountAsync((App.Session[Constant.CURRENTISSUENO_SESSION] as LotteryNumsInfo).IssueNo,
                    MainPage.playType, MainPage.playTypeRadio, GetBetNums());
                wcfclient.GetRemaindCountCompleted += (s, er) =>
                {
                    Dictionary<string, double> dic = er.Result;
                    string nums = GetBetNums();
                    if (MainPage.lotteryType == LotteryType.SSC || MainPage.lotteryType == LotteryType._3D)
                    {
                        for (int i = 0; i < nums.Length; i++)
                        {
                            if (dic.ContainsKey(nums.Substring(i, 1)))
                            {
                                //当前号码下注倍数与剩余注数比较
                                if ((Convert.ToDouble(lbEachNumPoint.Text) / Constant.OneBetPoint) >
                                    dic[nums.Substring(i, 1)])
                                {
                                    Messager.Show(string.Format("你购买的号码:{0}剩余注数已经不足您购买,请尝试减少倍数(下单分数)投注!",
                                        nums.Substring(i, 1)));
                                    isHandled = false;
                                    return;
                                }
                            }
                        }
                    }
                    else
                    {
                        string[] odds = nums.Split(',');
                        for (int i = 0; i < odds.Length; i++)
                        {
                            if (dic.ContainsKey(odds[i]))
                            {
                                //当前号码下注倍数与剩余注数比较
                                if ((Convert.ToDouble(lbEachNumPoint.Text) / Constant.OneBetPoint) >
                                    dic[odds[i]])
                                {
                                    Messager.Show(string.Format("你购买的号码:{0}剩余注数已经不足您购买,请尝试减少倍数(下单分数)投注!",
                                        odds[i]));
                                    isHandled = false;
                                    return;
                                }
                            }
                        }
                    }
                    srv.GetCapitalInfoAsync(App.Session[Constant.USERNAME_SESSION].ToString());
                };
            }
            else
                srv.GetCapitalInfoAsync(App.Session[Constant.USERNAME_SESSION].ToString());
        }

        void srv_GetCapitalInfoCompleted(object sender, GetCapitalInfoCompletedEventArgs e)
        {
            BetRecord record = new BetRecord();
            if (isShow)
                record.BetCount = BetCountCalc.GetBetCount
                   (NumBasket, (PlayType)PlayType, numPanel.isWriten,
                    ((PlayTypeRadio)Convert.ToInt32(rbPanel.GetChoosedRadioButton().Tag.ToString())).ToString()
                   );
            else
                record.BetCount = BetCountCalc.GetBetCount(numPanel.GetChoosedNum(), (PlayType)PlayType);
            record.BetMoney = record.BetCount * Convert.ToDouble(lbEachNumPoint.Text);
            if (isShow)//正向
            {
                if (e.Result == null || e.Result.EnableScores < record.BetMoney)
                {
                    Messager.Show("你的账户余额不足，请及时充值!");
                    isHandled = false;
                    return;
                }
                record.BetMultiple = Convert.ToDouble(lbEachNumPoint.Text) / Constant.OneBetPoint;
                record.BetTime = System.DateTime.Now;
                record.Direction = (int)Direction.Tag;
                record.UserID = App.Session[Constant.USERNAME_SESSION].ToString();
                record.ResultStatus = (int)BetStatusEnum.Bet;
                record.BetNums = GetBetNums();
                record.ResultStatus = 0;
                record.PlayTypeID = PlayType;
                record.LotteryTypeID = (int)lotteryType;
                record.EachNumsMoney = Convert.ToDouble(lbEachNumPoint.Text);
                record.PlayTypeName = PlayTypeName;
                record.PlayTypeRadioID = Convert.ToInt32(rbPanel.GetChoosedRadioButton().Tag);
                if (record.PlayTypeRadioID==48||record.PlayTypeRadioID==49||record.PlayTypeRadioID==50||record.PlayTypeRadioID==51||record.PlayTypeRadioID==53||record.PlayTypeRadioID==54)
                {
                    record.PlayTypeDirection = rbPanel.GetChoosedRadioButton().Content+"("+numPanel.sbTxt.ToString()+")" + "[" + Direction.Text + "]";
                }
                else
                {
                    record.PlayTypeDirection = rbPanel.GetChoosedRadioButton().Content + "[" + Direction.Text + "]";
                }
                record.OddBonus = isShow == true ? (lbScale.Text + "/" + lbBonus.Text) : GetOddsForNum(GetBetNums());
                record.BonusPct = isShow == true ? Convert.ToDouble(lbBackPct.Text.Replace("%", "")) : 0;
                record.WinCount = 0;
                record.WinMoney = 0;
                record.IsWin = 0;
                record.IssueNo = (App.Session[Constant.CURRENTISSUENO_SESSION] as LotteryNumsInfo).IssueNo;
                SureBet sb = new SureBet(record,isShow);
                sb.Closed += new EventHandler(sb_Closed);
                sb.Show();
            }
            else//逆向
            {
                List<BetRecord> br_list = new List<BetRecord>();
                string nums = GetBetNums();
                int count = 0;
                string[] odds = GetOddsForNum(GetBetNums()).Split(',');
                if (nums.IndexOf(",") > -1)
                    count = nums.Split(',').Count();
                else
                    count = nums.Length;
                double LostMoney = 0;
                for (int i = 0; i < count; i++)
                {
                    BetRecord bet = new BetRecord();
                    bet.BetCount = 1;
                    bet.EachNumsMoney = Convert.ToDouble(lbEachNumPoint.Text);
                    bet.BetMoney = bet.EachNumsMoney;
                    bet.BetMultiple = Convert.ToDouble(lbEachNumPoint.Text) / Constant.OneBetPoint;
                    bet.BetTime = System.DateTime.Now;
                    bet.Direction = (int)Direction.Tag;
                    bet.UserID = App.Session[Constant.USERNAME_SESSION].ToString();
                    bet.ResultStatus = (int)BetStatusEnum.Bet;
                    if (nums.IndexOf(",") > -1)
                    {
                        string[] n = nums.Split(',');
                        bet.BetNums = n[i];
                    }
                    else
                        bet.BetNums = nums.Substring(i, 1);
                    bet.ResultStatus = 0;
                    bet.PlayTypeID = PlayType;
                    bet.LotteryTypeID = (int)lotteryType;
                    bet.PlayTypeName = PlayTypeName;
                    bet.PlayTypeRadioID = Convert.ToInt32(rbPanel.GetChoosedRadioButton().Tag);
                    bet.PlayTypeDirection = rbPanel.GetChoosedRadioButton().Content + "[" + Direction.Text + "]";
                    bet.OddBonus = odds[i];
                    bet.BonusPct = 0;
                    bet.WinCount = 0;
                    bet.WinMoney = 0;
                    bet.IsWin = 0;
                    bet.IssueNo = (App.Session[Constant.CURRENTISSUENO_SESSION] as LotteryNumsInfo).IssueNo;
                    br_list.Add(bet);
                    LostMoney += (Convert.ToDouble(odds[i]) - 1) * bet.BetMoney;
                }
                if (e.Result == null || e.Result.EnableScores < record.BetMoney || e.Result.EnableScores < LostMoney)
                {
                    Messager.Show("你的账户余额不足或余额不足赔付本次逆向投注，请及时充值!");
                    isHandled = false;
                    return;
                }
                SureBet sb = new SureBet(br_list,isShow);
                sb.Closed += new EventHandler(sb_Closed);
                sb.Show();
            }
        }
        void sb_Closed(object sender, EventArgs e)
        {
            if (((SureBet)sender).DialogResult == true && ((SureBet)sender).isReturn == true)
            {
                btnClear_Click(btnClear, null);
                //LotteryServiceClient _proxy = WcfProxy.GetProxy;
                //_proxy.GetCapitalInfoCompleted += (s, er) =>
                //{
                //    MainPage.PersonalControl.DataContext = er.Result;
                //};
                //_proxy.GetCapitalInfoAsync(App.Session[Constant.USERNAME_SESSION].ToString());
                //if (!isShow)
                //    RefreshRateData();
            }
            isHandled = false;
            //MainPage.dicWs.Clear();
        }
        string GetOddsForNum(string num)
        {
            string result = string.Empty;
            List<Dictionary<string, string>> list = App.Session[Constant.REVERSEODDS_SESSION] as List<Dictionary<string, string>>;
            if (lotteryType == LotteryType.NSSQ)
            {
                string[] nums = num.Split(',');
                for (int i = 0; i < nums.Length; i++)
                {
                    if (list[0].ContainsKey(nums[i]))
                    {
                        result += (list[0][nums[i]] + ",");
                    }
                }
                return result.Length > 0 ? result.Substring(0, result.Length - 1) : result;
            }
            for (int i = 0; i < num.Length; i++)
            {
                if (list[0].ContainsKey(num.Substring(i, 1)))
                {
                    result += (list[0][num.Substring(i, 1)] + ",");
                }
            }
            return result.Length > 0 ? result.Substring(0, result.Length - 1) : result;
        }
        //void RefreshRateData()
        //{
        //    if (MainPage.lotteryTypeAll == LotteryType.NSSC//绑定逆向赔率
        //        || MainPage.lotteryTypeAll == LotteryType.N3D
        //        || MainPage.lotteryTypeAll == LotteryType.NSSQ)
        //    {
        //        LotteryServiceClient _srv = WcfProxy.GetProxy;
        //        _srv.GetOddsAsync(MainPage.playType, MainPage.playTypeRadio, (App.Session[Constant.CURRENTISSUENO_SESSION] as LotteryNumsInfo).IssueNo);
        //        _srv.GetOddsCompleted += (s, e) =>
        //        {
        //            if (MainPage.rateGrids != null)
        //            {
        //                foreach (RateGrid rg in MainPage.rateGrids)
        //                {
        //                    rg.DataSource = e.Result.ToList();
        //                    rg.BindData();
        //                }
        //            }
        //            App.Session[Constant.REVERSEODDS_SESSION] = e.Result.ToList();
        //        };
        //    }
        //}
    }
}
